package test;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.JOptionPane;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;

@WebServlet(name = "teststudent")
public class studentloginServlet extends HttpServlet {
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html");
        response.setCharacterEncoding("utf-8");
        PrintWriter out1= response.getWriter();
        //传值到jsp页面
        String id =request.getParameter("id");
        id = id.trim();

        String key =request.getParameter("key");
        key = key.trim();
        String submit =request.getParameter("submit");
        Connection con = null;
        Statement sql;
        ResultSet rs;
        try{
            Class.forName("com.mysql.cj.jdbc.Driver");
        }
        catch (Exception e){
            out1.println("<h1>" + e);
        }
        String url = "jdbc:mysql://localhost:3306/course?" + "useSSL=false&serverTimezone=GMT&characterEncoding=utf-8";
        String user = "root";
        String password = "123456";
        try {
            con = DriverManager.getConnection(url,user,password);
            sql = con.createStatement();
            String SQL = "select * from studentinfo";

            rs = sql.executeQuery(SQL);
            if (id == "" || key == ""){
            	out1.print("请输入用户名和密码");
            
            }
            while(rs.next()){
                if (id.equals(rs.getString(1)) && key.equals(rs.getString(3))) {
                	request.setAttribute( "id",id);
                    request.getRequestDispatcher("index.jsp").forward(request,response);
                   
                }else {   
                	out1.print("用户名或密码错误");
                }
            }
        }
        catch (SQLException e){
        	response.sendRedirect("login.jsp");
        	JOptionPane.showMessageDialog(null, "密码或用户名错误"+e,"错误",JOptionPane.ERROR_MESSAGE); 
        }
    }
    }


